package cn.acewill.yxd.yunxundian.ui.sign;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import cn.acewill.yxd.yunxundian.BaseActivity;
import cn.acewill.yxd.yunxundian.R;
import cn.acewill.yxd.yunxundian.YXDAPP;
import cn.acewill.yxd.yunxundian.adapter.YxdMajorMainAdpter;
import cn.acewill.yxd.yunxundian.adapter.YxdMinorMainAdpter;
import cn.acewill.yxd.yunxundian.model.RMain;
import cn.acewill.yxd.yunxundian.model.Schedule;
import cn.acewill.yxd.yunxundian.model.rJson;
import cn.acewill.yxd.yunxundian.model.sType;
import cn.acewill.yxd.yunxundian.model.tempLostRR;
import cn.acewill.yxd.yunxundian.pubClass.pubClass;
import cn.acewill.yxd.yunxundian.pubClass.reportQuery;
import cn.acewill.yxd.yunxundian.utils.CacheActivity;

/**
 * Created by AAA on 2017/4/21.
 */

public class YxdMajorMainActivity extends BaseActivity implements AdapterView.OnItemClickListener{

    protected YXDAPP yxdapp=new YXDAPP();
    protected DbManager db = x.getDb(yxdapp.getDaoConfig());
    private ListView majorItemList,minorItemList;
    private YxdMajorMainAdpter adapter;
    private YxdMinorMainAdpter minorAdapter;
    private ArrayList<RMain.TablesBean.RowsBean.Q2Bean> minorList;
    private  ArrayList<RMain> rMains;
    public static int schid;
    private  ArrayList<RMain.TablesBean.Q1Bean> myq1List;
    private ArrayList<RMain.TablesBean.RowsBean.Q2Bean> myq2List;
    private int checkPosition = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.yxd_select_itenmlist);
     //   CacheActivity.addActivity(this);
        initView();
    }
    public void initView(){
        schid=getIntent().getIntExtra("schid",0);
        Toolbar mytoolbar = (Toolbar) findViewById(R.id.myToolBar);
        mytoolbar.setTitle("");
        mytoolbar.setNavigationIcon(R.mipmap.back);
        setSupportActionBar(mytoolbar);
        mytoolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        this.majorItemList= (ListView) findViewById(R.id.majorItemList);
        this.minorItemList= (ListView) findViewById(R.id.minorItemList);
        minorItemList.setOnItemClickListener(this);
        initLostRR();
    }

    public void initLostRR(){
        try {
            setSelectColor();
            LoadInfo();
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        initLostRR();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_switch_point,menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.switchType:
                if (item.getTitle().equals("关键项")){
                    if (myq2List!=null&&myq1List.size()>0){
                        item.setTitle("全部项");
                    }
                    getAllPoint();
                }else{
                    item.setTitle("关键项");
                    try {
                        LoadInfo();
                    } catch (DbException e) {
                        e.printStackTrace();
                    }
                }
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    public void LoadInfo() throws DbException {
        if(schid==0)
        {
            WrittingEvaluationListActivity yea=new WrittingEvaluationListActivity();
            yea.jiuyuanSchid();
        }
        Schedule schedule=db.selector(Schedule.class).where("ID","=",schid).findFirst();
        sType type=db.selector(sType.class).where("ID","=",schedule.getSTypeID()).findFirst();
        rJson rmian = db.selector(rJson.class).where("ID", "=", type.getReportId()).findFirst();
//        }else{
//            rmian=db.selector(rJson.class).where("ID","=", FirstPageFragment.reportId).findFirst();
//        }
        String json= rmian.getjSon();
        Gson gson=new Gson();
        Type typeList = new TypeToken<ArrayList<RMain>>() {
        }.getType();
        rMains = gson.fromJson(pubClass.convertToArrayJsonNormal(json), typeList);
        /*大项集合*/
        ArrayList<RMain.TablesBean.Q1Bean> majorList = new ArrayList<>();
        List<RMain.TablesBean> TableList=rMains.get(0).getTables();
        for (int i=0;i<TableList.size();i++){
            RMain.TablesBean tablesBean=TableList.get(i);
            majorList.add(tablesBean.getQ1());
        }
        /*大项里面数据的绑定，点击刷新小项*/
        adapter=new YxdMajorMainAdpter(YxdMajorMainActivity.this, majorList,q1BeanList, new YxdMajorMainAdpter.BtnClick() {
            @Override
            public void click(int position) {
                adapter.setDefItem(position);//设置点击的背景
                checkPosition = position;
                setMinAdapter();
            }
        });
        majorItemList.setAdapter(adapter);
        adapter.setDefItem(checkPosition);
        //设置默认加载第一条数据
        setMinAdapter();

    }

    public void setMinAdapter(){
        List<RMain.TablesBean.RowsBean> rowlist=rMains.get(0).getTables().get(checkPosition).getRows();
        if (rowlist!=null&&rowlist.size()>0){
            minorList=new ArrayList<>();
            for (int i=0;i<rowlist.size();i++){
                RMain.TablesBean.RowsBean rowbean= rowlist.get(i);
                minorList.add(rowbean.getQ2());
            }
        }
        minorAdapter = new YxdMinorMainAdpter(YxdMajorMainActivity.this, minorList,q2BeanList);
        minorItemList.setAdapter(minorAdapter);
        minorAdapter.notifyDataSetChanged();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        RMain.TablesBean.RowsBean.Q2Bean bean = (RMain.TablesBean.RowsBean.Q2Bean) parent.getItemAtPosition(position);
        int checkNum=1;
        try {
            checkNum=checkAddFunction(bean);
        } catch (DbException e) {
            e.printStackTrace();
        }
        if(checkNum==0)
            return;
        Intent in=new Intent(this,MarkPhotoActivity.class);
        in.putExtra("title",bean.getReportRowName());
        in.putExtra("sName",bean.getSName());
        in.putExtra("type",bean.getItemType());
        in.putExtra("maxScore",bean.getMaxScore());
        in.putExtra("id",bean.getID());
        in.putExtra("tag",1);
        in.putExtra("schid",schid);
        startActivity(in);
    }


    public int checkAddFunction(RMain.TablesBean.RowsBean.Q2Bean rowBean) throws DbException
    {
        int retI=1;
        int typeNum=rMains.get(0).getQ().getCountFunc();
        if(typeNum==2)//2可重复
        {
            retI=1;
        }
        else// 0 1 不可重复
        {
            List<tempLostRR> trrList=db.selector(tempLostRR.class)
                    .where("schId","=",schid)
                    .and("rRowId","=",rowBean.getID())
                    .findAll();
            if(trrList!=null && trrList.size()>0)
            {
                BaseActivity.showAnimaDialog(this,"您已添加过该项失分项，此评估表设置为不能重复扣分");
                return 0;
            }
        }
        return retI;
    }

    //切换必填
    private void getAllPoint(){
        List<RMain.TablesBean> tables=rMains.get(0).getTables();
        //先找到控制的小项
        myq2List=new ArrayList<>();
        for (RMain.TablesBean table:tables){
            List<RMain.TablesBean.RowsBean> rowsBeen=table.getRows();
            for (RMain.TablesBean.RowsBean rows:rowsBeen){
                // TODO: 2017/9/5 实际设置2与3,此处为了测试 
                if (rows.getQ2().getIsPoint()>=2){
                    myq2List.add(rows.getQ2());
                }
            }
        }
        myq1List=new ArrayList<>();
        //根据q2的reportTableID找到对应的大项
        if ( myq2List!=null&& myq2List.size()>0){
            for (int i=0;i< myq2List.size();i++){
                int reportid= myq2List.get(i).getReportTableID();
                //将大项加入进去，不能重复
                for (RMain.TablesBean table:tables){
                    RMain.TablesBean.Q1Bean q1Been = table.getQ1();
                    if (q1Been.getID()==reportid){
                        if (myq1List.size()<=0){
                            myq1List.add(q1Been);
                        }else{ //集合是空的时候循环会报错
                            for (int k=0;k<myq1List.size();k++){
                                if (myq1List.get(k).getID()==q1Been.getID()){
                                    myq1List.remove(k);
                                    break;
                                }
                            }
                            myq1List.add(q1Been);
                        }
                    }
                }
            }
            //切换适配器
            adapter=new YxdMajorMainAdpter(this, myq1List, q1BeanList,new YxdMajorMainAdpter.BtnClick() {
                @Override
                public void click(int position) {
                    //根据id查询所有小项
                    adapter.setDefItem(position);
                    RMain.TablesBean.Q1Bean q1=myq1List.get(position);
                    ArrayList<RMain.TablesBean.RowsBean.Q2Bean> list=new ArrayList<>();
                    for (RMain.TablesBean.RowsBean.Q2Bean q2:myq2List){
                        if (q2.getReportTableID()==q1.getID()){
                            list.add(q2);
                        }
                    }
                    minorAdapter = new YxdMinorMainAdpter(YxdMajorMainActivity.this,list,q2BeanList);
                    minorItemList.setAdapter(minorAdapter);
                    minorAdapter.notifyDataSetChanged();
                }
            });
            majorItemList.setAdapter(adapter);
            adapter.notifyDataSetChanged();
            //设置默认的list
            int index=0;
            if (index==0){//只进入一次
                adapter.setDefItem(0);
                index++;
                RMain.TablesBean.Q1Bean q1=myq1List.get(0);
                ArrayList<RMain.TablesBean.RowsBean.Q2Bean> list=new ArrayList<>();
                for (RMain.TablesBean.RowsBean.Q2Bean q2:myq2List){
                    if (q2.getReportTableID()==q1.getID()){
                        list.add(q2);
                    }
                }
                minorAdapter = new YxdMinorMainAdpter(YxdMajorMainActivity.this,list,q2BeanList);
                minorItemList.setAdapter(minorAdapter);
                minorAdapter.notifyDataSetChanged();
            }

        }else{
            BaseActivity.showAnimaDialog(this,"当前评估表无必填评估项");
        }
    }

    List<RMain.TablesBean.RowsBean.Q2Bean> q2BeanList;
    List<RMain.TablesBean.Q1Bean> q1BeanList;
    //已选择的item设置颜色
    private void setSelectColor() throws DbException {
        q2BeanList=new ArrayList<>();
        q1BeanList = new ArrayList<>();
        List<tempLostRR> rrlist =  db.selector(tempLostRR.class).where("schId","=",schid).findAll();
       if (rrlist!=null&&rrlist.size()>0){
          for (tempLostRR rr : rrlist){
              if (rr.ischeck()){
                 RMain.TablesBean.RowsBean.Q2Bean bean = getRowByRowId(rr.getRRowId());
                 if (bean!=null) {
                     q2BeanList.add(bean);
                     q1BeanList.add(getQ1ByRowId(bean));
                 }
              }
           }
       }
    }

    public RMain.TablesBean.RowsBean.Q2Bean getRowByRowId(int rowid) {
        if(rMains != null){
            for (int i = 0; i < rMains.size(); i++) {
                List<RMain.TablesBean> tb = rMains.get(i).getTables();
                for (RMain.TablesBean t : tb) {
                    List<RMain.TablesBean.RowsBean> rbs = t.getRows();
                    for (RMain.TablesBean.RowsBean rb : rbs) {
                        if (rb.getQ2().getID() == rowid) {
                            return rb.getQ2();
                        }
                    }
                }
            }
        }
        return null;
    }
    public RMain.TablesBean.Q1Bean getQ1ByRowId(RMain.TablesBean.RowsBean.Q2Bean bean){
        if (rMains != null){
            for (int i = 0; i<rMains.size();i++){
                List<RMain.TablesBean> tb = rMains.get(i).getTables();
                for (RMain.TablesBean t : tb){
                    if (t.getQ1().getID() == bean.getReportTableID()){
                        return  t.getQ1();
                    }
                }
            }
        }
        return null;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }
}
